//
//  UserAccountViewController.swift
//  Weibo
//
//  Created by 明丽 on 16/1/15.
//  Copyright © 2016年 明丽. All rights reserved.
//

import UIKit
import AFNetworking


class UserAccountViewController: NSObject {
    //使用单例对象 第一次登陆的结果无法获取
    static let shareAccount = UserAccountViewController()

//账户模型属性
    var userAccount: UserAccount?
    
    override init() {
        userAccount = UserAccount.loadUserAccount()
        super.init()
    }
    //用户是否登录的标记
    //只读属性 计算型属性
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    
//从缓存中换取token
    var token: String? {
    
    
    return userAccount?.access_token
    }
    //用户名
    var userName: String? {
    return userAccount?.name
    
    }
//    //用户头像
    var headImageURL: NSURL? {
    
    return NSURL(string:userAccount?.avatar_large ?? "")
    }
    //用户的唯一标识的用户id
    var userId: String? {
        return userAccount?.uid
    }


//获取token授权
    func loadAccessToken(code : String,finished: (isSuccess: Bool) -> ()){
    let urlString = "https://api.weibo.com/oauth2/access_token"
    let parmeters = ["client_id":client_id,"client_secret": client_secret, "grant_type":"authorization_code","code": code,"redirect_uri": redirect_uri]
   NetworkTools.shardTools.requestJSONDict(urlString, paraneters: parmeters) { (dict, error) -> () in
    if error != nil {
    //程序走到这证明有错误
        finished(isSuccess: false)
        
    return
    
    }
    //请求成功
    let account = UserAccount(dict: dict!)
    //加载用户信息
    self.loadUserINfo(account,finished: finished)

    
        }
    }
    

    //MARK 加载用户信息
    private func loadUserINfo(account: UserAccount,finished: (isSuccess: Bool) -> () ) {

    // print(access_token,uid)
    let usrString = "https://api.weibo.com/2/users/show.json"
    let parameters = ["access_token": account.access_token!, "uid":account.uid!]
    let afn = AFHTTPSessionManager()
    afn.GET(usrString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        //print(result)
        guard let dict = result as? [String : AnyObject] else {
            print("数据不合法")
            finished(isSuccess: false)
            return
        }
        let name = dict["name"] as! String
        let avatar_large = dict["avatar_large"] as! String
        
        account.name = name
        account.avatar_large = avatar_large
        account.saveAccount()
        //执行成功的回调
        finished(isSuccess: true)
        
        
        }) { (_, error) -> Void in
            finished(isSuccess: false)
            print(".....",error)
    }
}
}

